<?php


namespace App\Model;


use App\Observers\GoodObserver;
use Encore\Admin\Auth\Database\Administrator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Good extends Model
{

    public $timestamps = false;

    protected $fillable = [
        'amazon_goods_id',
        'goods_img_url',
        'price',
        'casku',
        'uksku',
        'jpsku',
        'web_sku',
        'number',
        'color',
        'supplier',
        'photo_img_id',
        'ausku',
        'supplier_id',
    ];


    /**
     * 关联 amazon
     *
     * @return BelongsTo
     */
    public function amazonGood()
    {
        return $this->belongsTo(AmazonGood::class, 'amazon_goods_id');
    }


    /**
     * 关联 amazon
     *
     * @return BelongsTo
     */
    public function supplier()
    {
        return $this->belongsTo(Administrator::class, 'supplier_id');
    }

    /**
     * 关联备注
     *
     * @return HasMany
     */
    public function note()
    {
        return $this->hasMany(Note::class, 'goods_id');
    }

    /**
     * 关联最新的管理员备注
     *
     * @return HasOne
     */
    public function lastAdminNote()
    {
        return $this->hasOne(Note::class, 'goods_id')
            ->select(['content', 'goods_id'])
            ->where('user_user_id', 3)
            ->orderByDesc('id');
    }

    /**
     * 关联最新的客服备注
     *
     * @return HasOne
     */
    public function lastCustomNote()
    {
        return $this->hasOne(Note::class, 'goods_id')
            ->select(['content', 'goods_id'])
            ->where('user_user_id', '!=', 3)
            ->orderByDesc('id');
    }

    /**
     * 关联商品库存
     *
     * @return HasOne
     */
    public function totalStock()
    {
        return $this->hasOne(Stock::class, 'goods_id')->select([
            DB::raw("SUM(IF ( type = 1, `value`, -`value` )) as stock"),
            'goods_id'
        ])->groupBy('goods_id')->withDefault([
            'stock' => 0
        ]);
    }


    /**
     * 批量更新
     *
     * @param array $multipleData 批量更新二维数组[
     *  ['id' => 1(第一个字段为主键即 $primaryKey => primaryKeyValue ) ,'name' => , 其他字段...],
     *  ['id' => 1(第一个字段为主键即 $primaryKey => primaryKeyValue ) ,'name' => , 其他字段...],
     *  .......
     * ]
     *
     *
     * @return int|false 成功返回受影响行数 否则返回false
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2019年07月03日 15:18:46
     */
    public function updateBatch(array $multipleData)
    {
        if (!$multipleData) {
            return true;
        }
        try {
            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            //获取非主键字段名
            unset($updateColumn[0]);
            $whereIn = "";
            $q = "UPDATE " . $this->getTable() . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .= $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $this->getKeyName() . " = " . $data[$this->getKeyName()] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$this->getKeyName()] . "', ";
            }
            $query = rtrim($q, ", ") . " WHERE " . $this->getKeyName() . " IN (" . rtrim($whereIn, ', ') . ")";

            return DB::connection($this->getConnectionName())->update(DB::raw($query));
        } catch (\Exception $exception) {
            Log::info("批量更新失败" . $exception->getMessage());
            return false;
        }

    }


    /**
     * 更新库存
     *
     * @param array $update
     * @return bool
     * @author: 梅杰 2020/3/8 13:51
     */
    public function batchUpdateStock(array $update)
    {
        $sql = "INSERT INTO " . $this->getTable() . "(`id`,`stock`) VALUES" .
            implode(",", $update).
        "ON DUPLICATE KEY UPDATE stock = stock + VALUES(stock)";


        return DB::connection($this->getConnectionName())->insert(DB::raw($sql));

    }
}
